package com.getpebble.android.main.sections.mypebble.fragment;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.Toast;
import com.getpebble.android.PebbleApplication;
import com.getpebble.android.R;
import com.getpebble.android.common.core.trace.Analytics.MobileAppBehavior;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.core.util.PblPreferences;
import com.getpebble.android.common.core.util.PblPreferences.PrefKey;
import com.getpebble.android.common.framework.fragment.PblBaseFragment;
import com.getpebble.android.common.model.AppInfo;
import com.getpebble.android.common.model.FrameworkState;
import com.getpebble.android.common.model.FrameworkState.EventType;
import com.getpebble.android.common.model.PblDevice;
import com.getpebble.android.common.model.PblDeviceModel.PblDeviceRecord;
import com.getpebble.android.common.model.SideloadApp;
import com.getpebble.android.firmware.FirmwareUpdateCheckTask;
import com.getpebble.android.firmware.FirmwareUpdateCheckTask.Listener;
import com.getpebble.android.framework.FrameworkEventReceiver;
import com.getpebble.android.framework.FrameworkEventReceiver.IFrameworkEventListener;
import com.getpebble.android.framework.PblFrameworkInterface;
import com.getpebble.android.framework.developer.PblDeviceObserver.ConnectedDeviceChangeListener;
import com.getpebble.android.framework.firmware.FirmwareManifestBundle;
import com.getpebble.android.framework.util.SideloadingUtils;
import com.getpebble.android.framework.util.SideloadingUtils.BundleType;
import com.getpebble.android.main.activity.MainActivity;
import com.getpebble.android.main.fragment.FragmentMetaData.FragmentType;
import com.getpebble.android.main.sections.mypebble.adapter.LockerAppsPagerAdapter;
import com.getpebble.android.main.sections.mypebble.view.IconPageIndicator;
import com.getpebble.android.main.sections.mypebble.view.LoadedWatchappsContainerView;
import com.getpebble.android.main.sections.support.activity.FirmwareUpdateActivity;
import com.sun.mail.imap.protocol.ListInfo;
import com.sun.mail.smtp.SMTPMessage;

public class MyPebbleFragment extends PblBaseFragment {
    protected static String TAG = MyPebbleFragment.class.getSimpleName();
    private LockerAppsPagerAdapter mAdapter;
    private boolean mCanNagFirmware = false;
    private final ConnectedDeviceChangeListener mConnectedDeviceChangeListener = new ConnectedDeviceChangeListener() {
        public void notifyConnectedDeviceChanged() {
            Activity activity = MyPebbleFragment.this.getActivity();
            if (activity != null) {
                activity.runOnUiThread(new Runnable() {
                    public void run() {
                        MyPebbleFragment.this.updateForConnectedDevice();
                    }
                });
            }
        }
    };
    private PblFrameworkInterface mFrameworkInterface;
    private IconPageIndicator mIconPageIndicator;
    private boolean mIsFirmwareUpdateDialogShowing = false;
    private LoadedWatchappsContainerView mLoadedWatchappsContainer;
    private ViewPager mLockerViewPager;

    static /* synthetic */ class AnonymousClass13 {
        static final /* synthetic */ int[] $SwitchMap$com$getpebble$android$common$model$FrameworkState$EventType = new int[EventType.values().length];

        static {
            try {
                $SwitchMap$com$getpebble$android$common$model$FrameworkState$EventType[EventType.FILE_INSTALL_COMPLETE.ordinal()] = 1;
            } catch (NoSuchFieldError e) {
            }
            try {
                $SwitchMap$com$getpebble$android$common$model$FrameworkState$EventType[EventType.FILE_INSTALL_PROGRESS_CHANGED.ordinal()] = 2;
            } catch (NoSuchFieldError e2) {
            }
        }
    }

    public int getLayoutId() {
        return R.layout.fragment_my_pebble;
    }

    public void init(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Trace.debug(TAG, "Initializing MyPebbleFragment");
        MobileAppBehavior.logScreenOpened("MyPebble");
        this.mLockerViewPager = (ViewPager) container.findViewById(R.id.watchfaces_pager);
        this.mAdapter = new LockerAppsPagerAdapter(getActivity(), getLoaderManager(), getFragmentManager());
        this.mLockerViewPager.setAdapter(this.mAdapter);
        this.mLoadedWatchappsContainer = (LoadedWatchappsContainerView) container.findViewById(R.id.loaded_watchapps_container);
        this.mLoadedWatchappsContainer.setLoaderManager(getLoaderManager());
        this.mIconPageIndicator = (IconPageIndicator) container.findViewById(R.id.icon_page_indicator);
        this.mIconPageIndicator.setViewPager(this.mLockerViewPager);
        this.mFrameworkInterface = PebbleApplication.getFrameworkInterface();
    }

    private void initFirmwareNag() {
        Activity activity = getActivity();
        if (activity != null) {
            long lastNagTime = new PblPreferences(activity).getLongData(PrefKey.FIRMWARE_NAG_TIME, 0);
            if (System.currentTimeMillis() - lastNagTime > 259200000) {
                Trace.debug(TAG, "Can nag for firmware update");
                this.mCanNagFirmware = true;
                return;
            }
            Trace.debug(TAG, "Not time to nag yet, lastNagTime: " + lastNagTime);
        }
    }

    private void updateFirmwareNagTime() {
        Activity activity = getActivity();
        if (activity != null) {
            new PblPreferences(activity).setLongData(PrefKey.FIRMWARE_NAG_TIME, System.currentTimeMillis());
            this.mCanNagFirmware = false;
        }
    }

    public void redraw() {
        if (this.mLoadedWatchappsContainer != null) {
            this.mLoadedWatchappsContainer.redraw();
        }
    }

    public void onResume() {
        super.onResume();
        PebbleApplication.addConnectedDeviceChangeListener(this.mConnectedDeviceChangeListener);
        updateForConnectedDevice();
        initFirmwareNag();
        if (this.mCanNagFirmware) {
            checkForFirmwareUpdates();
        }
        handleArguments(getArguments());
    }

    public void onPause() {
        super.onPause();
        PebbleApplication.removeConnectedDeviceChangeListener(this.mConnectedDeviceChangeListener);
    }

    private void handleArguments(Bundle arguments) {
        final Activity activity = getActivity();
        if (activity == null) {
            Trace.error(TAG, "handleArguments: Activity was null");
        } else if (arguments == null) {
            Trace.error(TAG, "handleArguments: arguments were null");
        } else {
            final Uri sideloadingUri = (Uri) arguments.getParcelable("extra_sideloading_uri");
            if (sideloadingUri == null) {
                Trace.error(TAG, "handleArguments: sideLoadingUri was null");
                return;
            }
            PblDevice connectedDevice = PebbleApplication.getConnectedDevice();
            if (connectedDevice == null) {
                Trace.error(TAG, "handleArguments: Connected device was null");
                displayNoConnectedDeviceDialog(activity);
                return;
            }
            switch (arguments.getInt("extra_sideloading_type", 0)) {
                case SMTPMessage.RETURN_FULL /*1*/:
                    Trace.debug(TAG, "sideloading pbz: " + sideloadingUri);
                    displayFirmwareSideloadingDialog(activity, sideloadingUri);
                    break;
                case SMTPMessage.RETURN_HDRS /*2*/:
                    Trace.debug(TAG, "sideloading pbw: " + sideloadingUri);
                    FrameworkEventReceiver.registerFrameworkStateEventListener(new IFrameworkEventListener() {
                        public void onFrameworkStateChanged(FrameworkState newState) {
                            if (newState == null || newState.getLastEvent() == null) {
                                Trace.error(MyPebbleFragment.TAG, "onFrameworkStateChanged: newState or last event was null");
                            } else if (newState.getLastEvent().equals(EventType.APP_INFO_AVAILABLE)) {
                                AppInfo appInfo = newState.getAppInfo();
                                if (appInfo != null) {
                                    Trace.debug(MyPebbleFragment.TAG, "Got app info for: " + appInfo.getShortName());
                                    if (MyPebbleFragment.this.getFragmentManager() != null) {
                                        MyPebbleFragment.this.showSideloadingDialog(activity, sideloadingUri, appInfo);
                                    } else {
                                        Trace.error(MyPebbleFragment.TAG, "Unable to display sideloading dialog: null fragment manager");
                                    }
                                } else {
                                    Trace.error(MyPebbleFragment.TAG, "Got null appinfo");
                                    Toast.makeText(activity, R.string.fetch_app_info_failed, 1).show();
                                }
                                FrameworkEventReceiver.unregisterFrameworkStateEventListener(this);
                            }
                        }
                    });
                    this.mFrameworkInterface.fetchAppInfo(sideloadingUri);
                    break;
                case ListInfo.INDETERMINATE /*3*/:
                    Trace.debug(TAG, "sideloading pbl: " + sideloadingUri);
                    displayLanguagePackSideloadingDialog(connectedDevice, sideloadingUri);
                    break;
                default:
                    Toast.makeText(activity, R.string.something_went_wrong_message, 1).show();
                    break;
            }
            arguments.remove("extra_sideloading_uri");
            arguments.remove("extra_sideloading_type");
        }
    }

    private void showSideloadingDialog(final Context context, final Uri sideloadingUri, final AppInfo appInfo) {
        if (context == null) {
            Trace.error(TAG, "Faile to show sideloading dialog, context was null");
            return;
        }
        new Builder(context).setTitle(getString(R.string.my_pebble_load_external_app)).setMessage(String.format(getString(R.string.my_pebble_external_app_message), new Object[]{sideloadingUri})).setPositiveButton(getString(R.string.my_pebble_external_app_positive_button), new OnClickListener() {
            public void onClick(DialogInterface arg0, int arg1) {
                if (MyPebbleFragment.this.mLoadedWatchappsContainer == null) {
                    Trace.error(MyPebbleFragment.TAG, "mLoadedWatchappsContainer was null");
                    Toast.makeText(context, R.string.something_went_wrong_message, 0).show();
                    return;
                }
                LoadUnloadDialogFragment dialogFragment = new LoadUnloadDialogFragment();
                dialogFragment.setWatchApp(new SideloadApp(appInfo, sideloadingUri));
                dialogFragment.setIsPebbleFull(MyPebbleFragment.this.mLoadedWatchappsContainer.isPebbleFull());
                dialogFragment.show(MyPebbleFragment.this.getFragmentManager(), null);
            }
        }).setNegativeButton(getString(R.string.my_pebble_external_app_negative_button), new OnClickListener() {
            public void onClick(DialogInterface arg0, int arg1) {
            }
        }).show();
    }

    private void updateForConnectedDevice() {
        this.mLoadedWatchappsContainer.onConnectedDeviceUpdated();
        this.mAdapter.onConnectedDeviceUpdated();
    }

    private void checkForFirmwareUpdates() {
        PblDeviceRecord connectedDeviceRecord = PebbleApplication.getConnectedDeviceRecord();
        if (connectedDeviceRecord != null) {
            new FirmwareUpdateCheckTask(getActivity(), connectedDeviceRecord.pblDevice, connectedDeviceRecord.fwVersion, new Listener() {
                public void onFirmwareUpdateCheckComplete(PblDevice device, final FirmwareManifestBundle bundle) {
                    if (bundle == null) {
                        Trace.debug(MyPebbleFragment.TAG, "No firmware found");
                        return;
                    }
                    MobileAppBehavior.logFwUpdateAvailable(bundle.getNormalMetadata().getFriendlyVersion().getVersionTag(), bundle.getNormalMetadata().getUrl(), String.valueOf(bundle.getNormalMetadata().getTimestamp()));
                    Trace.info(MyPebbleFragment.TAG, "Found installable firmware!");
                    final Activity activity = MyPebbleFragment.this.getActivity();
                    if (activity != null) {
                        activity.runOnUiThread(new Runnable() {
                            public void run() {
                                int i;
                                int i2 = 1;
                                if (((MainActivity) activity).isTutorialRunning()) {
                                    i = 0;
                                } else {
                                    i = 1;
                                }
                                if (MyPebbleFragment.this.mIsFirmwareUpdateDialogShowing) {
                                    i2 = 0;
                                }
                                if ((i & i2) != 0) {
                                    MyPebbleFragment.this.displayFirmwareUpdateAvailableDialog(bundle);
                                }
                            }
                        });
                    }
                }

                public void onInRecoveryMode(PblDevice device) {
                }
            }).submit();
        }
    }

    private void displayFirmwareUpdateAvailableDialog(final FirmwareManifestBundle bundle) {
        this.mIsFirmwareUpdateDialogShowing = true;
        final Activity activity = getActivity();
        if (activity == null) {
            Trace.error(TAG, "displayFirmwareUpdateAvailableDialog: Activity was null");
            return;
        }
        new Builder(activity).setTitle(getString(R.string.my_pebble_firmware_update_available)).setMessage(getString(R.string.my_pebble_ask_install_new_firmware)).setPositiveButton(R.string.my_pebble_install, new OnClickListener() {
            public void onClick(DialogInterface dialogInterface, int i) {
                MyPebbleFragment.this.mIsFirmwareUpdateDialogShowing = false;
                dialogInterface.dismiss();
                Intent intent = new Intent(activity, FirmwareUpdateActivity.class);
                intent.putExtra("extra_firmware_notes", bundle.getNormalMetadata().getNotes());
                intent.putExtra("extra_firmware_url", bundle.getNormalMetadata().getUrl());
                MyPebbleFragment.this.startActivity(intent);
            }
        }).setNegativeButton(R.string.text_not_now, new OnClickListener() {
            public void onClick(DialogInterface dialogInterface, int i) {
                MyPebbleFragment.this.updateFirmwareNagTime();
                MyPebbleFragment.this.mIsFirmwareUpdateDialogShowing = false;
                dialogInterface.dismiss();
            }
        }).setCancelable(false).show();
    }

    private void displayFirmwareSideloadingDialog(final Context context, final Uri sideloadingUri) {
        if (context == null) {
            Trace.error(TAG, "Failed to display firmware sideloading dialog: context was null.");
            return;
        }
        new Builder(context).setTitle(getString(R.string.my_pebble_load_untrusted_bundle)).setMessage(String.format(getString(R.string.my_pebble_untrusted_bundle_message), new Object[]{sideloadingUri})).setPositiveButton(R.string.my_pebble_install, new OnClickListener() {
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
                Intent intent = new Intent(context, FirmwareUpdateActivity.class);
                String sideloadingNotes = "";
                if (MyPebbleFragment.getFileDisplayName(context, sideloadingUri) != null) {
                    sideloadingNotes = String.format(MyPebbleFragment.this.getString(R.string.my_pebble_custom_firmware_bundle), new Object[]{uriFileName});
                }
                intent.putExtra("extra_firmware_notes", sideloadingNotes);
                intent.putExtra("extra_firmware_url", sideloadingUri.toString());
                MyPebbleFragment.this.startActivity(intent);
            }
        }).setNegativeButton(17039360, new OnClickListener() {
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        }).setCancelable(false).show();
    }

    private void displayLanguagePackSideloadingDialog(PblDevice connectedDevice, Uri sideloadingUri) {
        Trace.debug(TAG, "displayLanguagePackSideloadingDialog: " + sideloadingUri);
        final Activity activity = getActivity();
        if (activity == null) {
            Trace.debug(TAG, "Not displaying dialog; activity is null");
            return;
        }
        final ProgressDialog progressDialog = new ProgressDialog(activity);
        final Uri uri = sideloadingUri;
        final PblDevice pblDevice = connectedDevice;
        OnClickListener onInstallClickListener = new OnClickListener() {
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
                progressDialog.setMax(100);
                progressDialog.setMessage("Installing");
                progressDialog.setProgress(0);
                progressDialog.setProgressStyle(1);
                progressDialog.setCancelable(false);
                progressDialog.show();
                Toast.makeText(activity, "Installing!", 1).show();
                FrameworkEventReceiver.registerFrameworkStateEventListener(new IFrameworkEventListener() {
                    public void onFrameworkStateChanged(FrameworkState newState) {
                        if (newState.getLastEvent() != null) {
                            switch (AnonymousClass13.$SwitchMap$com$getpebble$android$common$model$FrameworkState$EventType[newState.getLastEvent().ordinal()]) {
                                case SMTPMessage.RETURN_FULL /*1*/:
                                    Trace.debug(MyPebbleFragment.TAG, "File install complete");
                                    FrameworkEventReceiver.unregisterFrameworkStateEventListener(this);
                                    progressDialog.dismiss();
                                    return;
                                case SMTPMessage.RETURN_HDRS /*2*/:
                                    Trace.debug(MyPebbleFragment.TAG, "File install progress changed; progress: " + newState.getFileInstallProgress());
                                    progressDialog.setProgress(newState.getFileInstallProgress());
                                    return;
                                default:
                                    return;
                            }
                        }
                    }
                });
                Uri uriToTemporaryFile = null;
                if (SideloadingUtils.isContentScheme(uri)) {
                    uriToTemporaryFile = Uri.fromFile(SideloadingUtils.downloadContentUriToFile(activity, uri, BundleType.LANGUAGE));
                }
                MyPebbleFragment.this.mFrameworkInterface.installLanguage(pblDevice, uriToTemporaryFile != null ? uriToTemporaryFile : uri, "", 0);
            }
        };
        String uriFileName = getFileDisplayName(activity, sideloadingUri);
        new Builder(activity).setTitle(R.string.my_pebble_load_external_language).setMessage(String.format(getString(R.string.my_pebble_external_language_message), new Object[]{uriFileName})).setPositiveButton(R.string.my_pebble_external_app_positive_button, onInstallClickListener).setNegativeButton(R.string.my_pebble_external_app_negative_button, new OnClickListener() {
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        }).setCancelable(true).show();
    }

    private static String getFileDisplayName(Context context, Uri sideloadingUri) {
        if (sideloadingUri.toString().endsWith(".pbz") || sideloadingUri.toString().endsWith(".pbl")) {
            String[] parts = sideloadingUri.toString().split("/");
            return parts[parts.length - 1];
        } else if (SideloadingUtils.isContentScheme(sideloadingUri)) {
            return SideloadingUtils.getContentName(context.getContentResolver(), sideloadingUri);
        } else {
            Trace.debug(TAG, "Unable to figure out filename for: " + sideloadingUri);
            return null;
        }
    }

    private void displayNoConnectedDeviceDialog(final Activity activity) {
        if (activity == null || (activity instanceof MainActivity)) {
            new Builder(activity).setTitle(R.string.my_pebble_no_device_connected).setMessage(R.string.my_pebble_cannot_load_while_disconnected).setPositiveButton(17039370, new OnClickListener() {
                public void onClick(DialogInterface dialogInterface, int i) {
                    activity.switchFragmentByType(FragmentType.CONNECTION_MANAGER, null);
                }
            }).setCancelable(true).show();
        } else {
            Trace.error(TAG, "displayNoConnectedDeviceDialog: failed to display dialog.");
        }
    }
}
